<?php

error_reporting(E_ALL);

class Panier
{
	private $nom_panier;
	private $structure_panier;
	private $nb_panier;
	
	
	// CONSTRUCTEUR
	
	public function __construct($nom_panier, $structure_panier)
	{
		$this->nom_panier = $nom_panier;
		$this->structure_panier = $structure_panier;
		$this->nb_panier = 0;
		$this->chargePanier();
	}
	
	
	// METHODES PUBLIQUES
	
	public function Ajoute($values)
	{
		if (count($values) == count($this->structure_panier))
		{
			for ($i = 0; $i < count($values); $i++)
			{
				$_SESSION[$this->nom_panier][$this->nb_panier][$this->structure_panier[$i]] = $values[$i];
			}
			$this->nb_panier++;
		}
	}
	
	public function Supprime($search_value, $search_index)
	{
		if (isset($_SESSION[$this->nom_panier]) and $this->structExiste($search_index))
		{
			$i = 0;
			foreach($_SESSION[$this->nom_panier] as $field)
			{
				if ($i < count($_SESSION[$this->nom_panier]) and $search_value == $_SESSION[$this->nom_panier][$i][$search_index])
				{
					unset($_SESSION[$this->nom_panier][$i]);
					$this->nb_panier--;
					array_splice($_SESSION[$this->nom_panier], $i, 0); // tasse le tableau
				}
				$i++;
			}
		}
	}
	
	public function Modifie($search_value, $search_index, $change_index, $new_value)
	{
		if (isset($_SESSION[$this->nom_panier]) and $this->structExiste($search_index) and $this->structExiste($change_index))
		{
			$i = 0;
			foreach($_SESSION[$this->nom_panier] as $field)
			{
				if ($i < count($_SESSION[$this->nom_panier]) and $search_value == $_SESSION[$this->nom_panier][$i][$search_index])
				{
					$_SESSION[$this->nom_panier][$i][$change_index] = $new_value;
				}
				$i++;
			}
		}
	}
	
	public function VidePanier()
	{
		unset($_SESSION[$this->nom_panier]);
		$this->nb_panier = 0;
	}
	
	public function getNbPanier()
	{
		return $this->nb_panier;
	}
	
	public function getStruct()
	{
		return $this->structure_panier;
	}
	
	public function getPanier()
	{		
		return isset($_SESSION[$this->nom_panier]) ? $_SESSION[$this->nom_panier] : null;
	}
	
	
	// METHODES PRIVEES
	
	private function chargePanier()
	{
		if (isset($_SESSION[$this->nom_panier]))
		{
			foreach($_SESSION[$this->nom_panier] as $field)
			{
				$i = 0;
				foreach($this->structure_panier as $struct)
				{
					$creation_ligne[$i] = $field[$struct];
					$i++;
				}
				
				$this->Ajoute($creation_ligne);
			}
		}
	}
	
	private function structExiste($struct)
	{
		return (in_array($struct, $this->structure_panier)) ? true : false;
	}
}

?>